var gulp = require('gulp');
var less = require('gulp-less');
var rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var imgmin = require('gulp-imagemin');
var connect = require('gulp-connect'); //用于生成本地服务器及实现热加载功能
var jsmin = require('gulp-uglify');
// var express = require('express');
var proxy = require('http-proxy-middleware');
// var Proxy = require('gulp-connect-proxy');

/*
gulp.task('jsmin', function(){
  gulp.src('./src/js/fastclick.js')
    .pipe(jsmin())
    .pipe(rename({suffix: '.min'}))
    .pipe(gulp.dest('./dist/js/'))
})
*/
gulp.task('lessTocss', function(){
  gulp.src('./src/css/*.less')
    .pipe(less())
    .pipe(autoprefixer())
    .pipe(gulp.dest('./dist/css/'))
    .pipe(connect.reload());
})
gulp.task('imgmin', function(){
  gulp.src('./src/image/*')
    .pipe(imgmin())
    .pipe(gulp.dest('./dist/image/'))
    .pipe(connect.reload());
})
/*
gulp.task('js', function(){
  gulp.src('./src/js/*')
    .pipe(gulp.dest('./dist/js/'))
    .pipe(connect.reload());
})
*/
gulp.task('jsmin', function(){
  gulp.src('./src/js/*.js')
    .pipe(jsmin())
    .pipe(gulp.dest('./dist/js/'))
    .pipe(connect.reload());
})
gulp.task('html', function(){
  gulp.src('./src/*.html')
    .pipe(gulp.dest('./dist/'))
    .pipe(connect.reload());
})
gulp.task('reload', function(){
  gulp.src('./src/*')
    .pipe(connect.reload());
  console.log('html change')
})
gulp.task('watch', function(){
  gulp.watch('./src/css/*.less', ['lessTocss']);
  gulp.watch('./src/image/*', ['imgmin']);
  gulp.watch('./src/*.html', ['html']);
  gulp.watch('./src/js/*.js', ['jsmin']);
  // gulp.watch('./src/js/*', ['js']);
})
gulp.task('server', function(){
  connect.server({
    root:'./dist',
    livereload: true,
    port: 8080,
    middleware: function(connect, opt) {
      return [
        proxy('/api', {
          target: 'http://localhost:3001',
          changeOrigin:true,
          pathRewrite: {
            '^/api': ''
          }
        })
      ]
    }
  })
})
gulp.task('default', ['server','watch','lessTocss', 'imgmin', 'jsmin', 'html', 'watch']);